package com.stars.empoly.vmodel

import android.app.Application
import android.text.Editable
import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.hwangjr.rxbus.RxBus
import com.stars.empoly.activity.BillActivity
import com.stars.empoly.componnent.CpAlipay
import com.stars.empoly.config.ConfigRx
import com.stars.empoly.model.RechargeBean
import com.stars.empoly.model.User
import com.stars.empoly.utils.net.NetEngine
import com.stars.empoly.view.SimpleTextWatcher
import com.trailer.base.base.BRepository
import com.trailer.base.base.BViewModel
import com.trailer.base.utils.UiSwitch
import kotlinx.coroutines.launch

class BalanceVModel(application: Application) : BViewModel<BRepository>(application) {

    var user= MutableLiveData<User>()
    var list=MutableLiveData<List<RechargeBean>>()
    //充值的id
    var payId:String?=null
    var payMoney:String?=null

    var money:String?=null

    var isType=MutableLiveData<String>()





    var oldText = ""
    var textWatcher = object : SimpleTextWatcher() {
        override fun afterTextChanged(s: Editable?) {
            super.afterTextChanged(s)
            var content = s.toString()
            if (!TextUtils.isEmpty(oldText) && content == oldText) {
                return
            }
            money = content
            oldText = content
            payMoney=null
            //刷新
            isType.value="1"
        }

    }

    fun getUserInfo(){
        viewModelScope.launch {
            var it=repository().lreq { NetEngine.service.getUser() }
            if(it.ok()){
                user.value=it.data

            }else{
            }
        }
    }


    fun toLook(){//查看明细


        UiSwitch.single(repository().context, BillActivity::class.java)


    }

    fun getReCharge(){
        viewModelScope.launch {
            var it=repository().lreq { NetEngine.service.rechargeConfig() }
            if(it.ok()){
                list.value=it.data
            }
        }
    }

    fun toPay(payType:String?){

        viewModelScope.launch{
            var it=repository().lreq { NetEngine.service.rechargePay(money,payId,payType) }
            if(it.ok(true)){

                if(payType=="2") {

                    getUserInfo()
                    //(repository().context as Activity).finish()
                    //刷新
                    RxBus.get().post(ConfigRx.REFRESH_USER, "")
                }
                if(payType=="3"){//支付宝

                    val orderInfo = it.data?.alipay
                    CpAlipay.pay(repository().context!!, orderInfo!!)


                }

            }
        }

    }


}
